/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package work.base.jvm;

import java.util.HashMap;

/**
 * @author Sakura Shen
 * @description
 * @date 2021/10/11
 */
public class JvmTest01 {


    public final static int OUTOFMEMORY = 200000000;

    private String oom;

    private int length;

    StringBuffer tempOOM = new StringBuffer();

    public JvmTest01(int leng) {
        this.length = leng;

        int i = 0;
        while (i < leng) {
            i++;
            try {
                tempOOM.append("a");
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                break;
            }
        }
        this.oom = tempOOM.toString();

    }

    public String getOom() {
        return oom;
    }

    public int getLength() {
        return length;
    }

    public static void main(String[] args) {

//        JvmTest javaHeapTest = new JvmTest(OUTOFMEMORY);
//        System.out.println(javaHeapTest.getOom().length());

        showJvm();
        // 64MB大小
        byte[] placeholder = new byte[64 * 1024 * 1024];
        showJvm();
    }

    /**
     * JVM 参数 -Xmx1024m -Xms512m -XX:+PrintGCDetails -XX:MaxTenuringThreshold=8
     */
    public static void showJvm() {
        Runtime run = Runtime.getRuntime();

        long maxMemory = Runtime.getRuntime().maxMemory();
        long totalMemory = Runtime.getRuntime().totalMemory();
        long freeMemory = Runtime.getRuntime().freeMemory();
        long usableMemony = maxMemory - totalMemory + freeMemory;
        System.out.println("可以获得最大内存是："+ maxMemory/1024/1024 + "M");
        System.out.println("已分配到的内存大小是："+ totalMemory/1024/1024 + "M");
        System.out.println("所分配内存的剩余大小是："+ freeMemory/1024/1024 + "M");
        System.out.println("最大可用内存大小是："+ usableMemony/1024/1024 + "M");
    }
}
